<?php

namespace App\Http\Controllers\Api;

use App\AuthorizerInfo;
use App\Classify;
use App\Http\Services\DomainManager;
use App\Http\Services\ToolsManager;
use App\IndexMessage;
use App\Merchant;
use App\MerchantDeliveryMethod;
use App\MerchantMedicine;
use App\OperatingCity;
use App\OrderItem;
use App\Orders;
use App\ShopCart;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\BadRequestException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;

class OtherController extends Controller
{
    public function getOperatingCity(){
        $cities=OperatingCity::whereStatus(1)->get();
        return response()->json(['level'=>'success','message'=>'success','data'=>$cities]);
    }

    public function getIndexMessage(){
        $message=IndexMessage::whereStatus(1)->orderByDesc('id')->limit(10)->get();
        if (count($message) > 0){
            foreach ($message as $item){
                if (!is_null($item->exp_time)){
                    if ($item->exp_time < time()){
                        $item->status=0;
                        $item->save();
                    }
                }
            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$message]);
    }

    //授权事件接收URL
    public function thirdPartyPlatformAuthHandle(Request $request){
        $token=sha1(md5('wxopen.dindong.cn'));//14f887f446ae3d77eb1b8f6a6ec53921d29d7398
        $key=substr(sha1('wxopen.dindong.cn').md5($token),0,43);//7468146a4f7916bdd817ec65da7308b78e47752e27c

        $token=sha1(md5('yaogeeks.dindong.cn'));//f6effe41cbe6fc9e45feb2b88d907a3c2a0ecaf9
        $key=substr(sha1('yaogeeks.dindong.cn').md5($token),0,43);//3e42b4a03fa0b6783335d054f168f7ff989a69bec5c

        $domain=DomainManager::getDomain($request);
        $token=sha1(md5($domain));
        $key=substr(sha1($domain).md5($token),0,43);

        $appid='';
        $secret='';

        $openConfig=WeChatThirdController::getPlatformConfig();

        if ($domain){
            if ($domain=='wxopen.dindong.cn'){
                $config=[
                    'app_id'=>env('COMPONENT_APPID'),
                    'secret'=>env('COMPONENT_SECRET'),
                    'token'=>'14f887f446ae3d77eb1b8f6a6ec53921d29d7398',
                    'aes_key'=>'7468146a4f7916bdd817ec65da7308b78e47752e27c'
                ];
            } else {
                $config=[
                    'app_id'    => $openConfig['app_id'] ?? $appid,
                    'secret'    => $openConfig['secret'] ?? $secret,
                    'token'     => $openConfig['token'] ?? $token,
                    'aes_key'   => $openConfig['aes_key']?? $key
                ];
            }

//            if ($domain=='yaogeeks.dindong.cn'){
//
//            }

        } else {
            return 'success';
        }


        Log::notice(
            'AUTH MESSAGE:$domain=>' .$domain
            .';Config-APPID:'.$config['app_id']
            .';Config-SECRET:'.$config['secret']
            .';Config-TOKEN:'.$config['token']
            .';Config-AES_KEY:'.$config['aes_key']);

        if (!$config['app_id'] || !$config['secret'])
            return 'success';



        try {
            $openPlatform = Factory::openPlatform($config);
            $server     =$openPlatform->server;
//            return $server->serve();
//            $response   =$server->serve();
            $server->push(function ($message) {
                if ($message['InfoType'] == 'unauthorized') {
                    //这里是取消授权
                    $attributes = [
                        'authorizer_appid' => $message['AuthorizerAppid']
                    ];
                    $values = [
                        'status' => 2,
                    ];
                    $record = AuthorizerInfo::updateOrCreate($attributes, $values);
                }
                if ($message['InfoType'] == 'updateauthorized') {
                    //这里是更新授权
                    $attributes = [
                        'authorizer_appid' => $message['AuthorizerAppid']
                    ];
                    $values = [
                        'auth_code' => $message['AuthorizationCode'],
                    ];
                    $record = AuthorizerInfo::updateOrCreate($attributes, $values);
                }
                if ($message['InfoType'] == 'authorized') {
                    //这里是授权成功
                    $attributes = [
                        'authorizer_appid' => $message['AuthorizerAppid']
                    ];
                    $values = [
                        'auth_code' => $message['AuthorizationCode'],
                        'status' => 1,
                    ];
                    $record = AuthorizerInfo::updateOrCreate($attributes, $values);
                };
            });
            return $server->serve();

        } catch (InvalidArgumentException $e) {
            Log::error('thirdPartyPlatformAuthHandle ERROR:InvalidArgumentException:'.$e->getMessage());
        } catch (\ReflectionException $e) {
            Log::error('thirdPartyPlatformAuthHandle ERROR:ReflectionException:'.$e->getMessage());
        } catch (BadRequestException $e) {
            Log::error('thirdPartyPlatformAuthHandle ERROR:BadRequestException:'.$e->getMessage());
        } catch (InvalidConfigException $e) {
            Log::error('thirdPartyPlatformAuthHandle ERROR:InvalidConfigException:'.$e->getMessage());
        }catch (\Exception $exception){
            Log::error('thirdPartyPlatformAuthHandle ERROR:Exception:'.$exception->getMessage());
        }catch (RuntimeException $e) {
            Log::error('RuntimeException:'.$e->getMessage());
        }

        return 'success';

    }

    /**
     * 消息与事件接收URL
     * @param $app_id
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function thirdPartyPlatformMessageHandle($app_id){
        $config=[
            'app_id'=>env('COMPONENT_APPID'),
            'secret'=>env('COMPONENT_SECRET'),
            'token'=>'f6effe41cbe6fc9e45feb2b88d907a3c2a0ecaf9',
            'aes_key'=>'3e42b4a03fa0b6783335d054f168f7ff989a69bec5c'
        ];
        $openPlatform = Factory::openPlatform($config);
        $server=$openPlatform->server;
        return $server->serve();
//        return 'success';
    }

    public function initMerchant(Request $request){
        $thisMerchant=Merchant::all();
        if (count($thisMerchant) > 0){
            foreach ($thisMerchant as $item){
                $array=[];
                $method=MerchantDeliveryMethod::whereMerchantId($item->id)->get();
                if (count($method) > 0){
                    foreach ($method as $value){
                        array_push($array,$value->delivery_method);
                    }
                    $item->support_delivery_method=json_encode($array);
                    $item->save();
                }

            }
        }

        return 1;
    }

    public function test(Request $request){
        dump(ToolsManager::getDistanceByAddress('广州塔',1,1));
    }

    /**
     * 订单超市取消
     * @return string
     */
    public function orderOverTime(){
        $orderList = Orders::whereStatus(1)->where('created_at','<=',date("Y-m-d H:i:s",time() - 24 * 3600))->get();
        if(count($orderList) > 0){
            foreach ($orderList as $order) {
                $order->status = 6;
                $order->save();

                /** @var OrderItem $orderItem */
                $orderItemList= OrderItem::getOrderItem($order->id);
                if(count($orderItemList) > 0){
                    foreach ($orderItemList as $orderItem) {
                        $thisMedicine=MerchantMedicine::whereId($orderItem->merchant_medicine_id)->first();
                        if($thisMedicine){
                            $thisMedicine->stock += $orderItem->num;
                            $thisMedicine->save();
                        }
                    }
                }
            }
        }

        return 'success';
    }

    /**
     * 订单超时自动收货
     * @return string
     */
    public function overTimeConfirmReceive(){
        $orderList = Orders::whereStatus(3)->where('express_time','<=',date("Y-m-d H:i:s",time() - 7 *24 * 3600))->get();
        if(count($orderList) > 0){
            foreach ($orderList as $order) {
                $order->status= 4;
                $order->receive_time= date('Y-m-d H:i:s',time());
                $order->save();
            }
        }

        return 'success';
    }

    /**
     * 购物车超时清空
     * @return string
     * @throws \Exception
     */
    public function shopCartOverTimeEmpty(){
        /** @var ShopCart $shopCart */
        $shopCartList = ShopCart::where('created_at','<=',date("Y-m-d H:i:s",time() - 24 * 3600))->get();
        if(count($shopCartList) > 0){
            foreach ($shopCartList as $shopCart) {
                $shopCart->delete();
            }
        }

        return 'success';
    }
}
